/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
// 相位数据管理模型
import store from '../../../store/index'
export default class PhaseDataMgr {
  constructor (originphaselist) {
    this.globalParamModel = store.getters.globalParamModel
    this.id = 1
    this.originphaselist = originphaselist // 初始上载的相位数组
    this.originphaseMap = new Map()
    this.lanecommonphaseMap = new Map() // 关联了相位的渠化车道数据（实时变化）
    this.lastLanecommonphaseMap = new Map()
    this.associatedphaselist = [] // 相位关联列表显示的相位方向（初始上载相位数据被关联了相位的渠化车道覆盖）
    this.associatedphaseMap = new Map()
    this.createOriginPhaseData()
  }
  createOriginPhaseData () {
    // 根据渠化变化前的上载的相位数据，生成初始数据，后续如果有相位的增加、删除，会变化，或者离开渠化再进来才会再次更新
    let originphaselist = JSON.parse(JSON.stringify(this.originphaselist))
    this.originphaseMap = new Map()
    for (let i = 0; i < originphaselist.length; i++) {
      this.originphaseMap.set(originphaselist[i].id, originphaselist[i])
    }
    console.log('originphasemap', this.originphaseMap)
    this.updateAssophaseList()
  }
  createTempLanePhase (Motorways, editobj, choosephaseid) {
    let TempLaneMap = new Map()
    let curMotorways = JSON.parse(JSON.stringify(Motorways))
    let tempeditobj = JSON.parse(JSON.stringify(editobj))
    tempeditobj.phaseid = choosephaseid
    tempeditobj.phaselabel = `P${choosephaseid}`
    this.changeItem(tempeditobj, ['phaseid', 'phaselabel'], curMotorways)
    for (let i = 0; i < curMotorways.length; i++) {
      let motorobj = curMotorways[i]
      let motorphaseid = motorobj.phaseid
      if (motorphaseid !== undefined) {
        // 处理已经关联了相位的渠化车道
        // motorphaseid !== undefined 证明已经关联相位，以此生成关联列表，数据驱动就不用处理删除修改等情况
        let lanephasedir = {}
        if (motorobj.direction) {
          lanephasedir.direction = motorobj.direction
        }
        if (motorobj.peddirection) {
          lanephasedir.peddirection = motorobj.peddirection
        }
        if (TempLaneMap.get(motorphaseid) === undefined) {
          TempLaneMap.set(motorphaseid, lanephasedir)
        } else {
          // 若有别的渠化车道关联了此相位，需要和当前渠化车道的方向叠加
          let laneassociatedphase = TempLaneMap.get(motorphaseid)
          if (motorobj.direction) {
            laneassociatedphase.direction = Array.from(new Set([...laneassociatedphase.direction, ...motorobj.direction]))
          }
          if (motorobj.peddirection) {
            laneassociatedphase.peddirection = Array.from(new Set([...laneassociatedphase.peddirection, ...motorobj.peddirection]))
          }
          TempLaneMap.set(motorphaseid, laneassociatedphase)
        }
      }
    }
    console.log(TempLaneMap)
    return this.createTempAssophaseList(TempLaneMap)
  }
  updateLanePhaseAssociatedMap (Motorways) {
    // 渠化图车道数据，更新key为phaseid的Map
    this.lanecommonphaseMap = new Map()
    let curMotorways = JSON.parse(JSON.stringify(Motorways))
    for (let i = 0; i < curMotorways.length; i++) {
      let motorobj = curMotorways[i]
      let motorphaseid = motorobj.phaseid
      if (motorphaseid !== undefined) {
        // 处理已经关联了相位的渠化车道
        // motorphaseid !== undefined 证明已经关联相位，以此生成关联列表，数据驱动就不用处理删除修改等情况
        let lanephasedir = {}
        if (motorobj.direction) {
          lanephasedir.direction = motorobj.direction
        }
        if (motorobj.peddirection) {
          lanephasedir.peddirection = motorobj.peddirection
        }
        if (this.lanecommonphaseMap.get(motorphaseid) === undefined) {
          this.lanecommonphaseMap.set(motorphaseid, lanephasedir)
        } else {
          // 若有别的渠化车道关联了此相位，需要和当前渠化车道的方向叠加
          let laneassociatedphase = this.lanecommonphaseMap.get(motorphaseid)
          if (motorobj.direction) {
            laneassociatedphase.direction = Array.from(new Set([...laneassociatedphase.direction, ...motorobj.direction]))
          }
          if (motorobj.peddirection) {
            laneassociatedphase.peddirection = Array.from(new Set([...laneassociatedphase.peddirection, ...motorobj.peddirection]))
          }
          this.lanecommonphaseMap.set(motorphaseid, laneassociatedphase)
        }
      }
    }
    console.log('lanecommonphaseMap', this.lanecommonphaseMap)
    this.updateAssophaseList()
  }
  checkSameDirectionPhase (curlanedirection, choosephaseid, lastchoosephaseid, tempMotorways, editobj) {
    // 校验同方向车道关联相位
    // 1. lastchoosephaseid不存在，说明是车道首次关联相位：
    // 仅需判断当前相位列表AssophaseList中，相位id !== choosephaseid的相位数据中，direction若包含curlanedirection其中一个方向，则校验不通过
    // 2. lastchoosephaseid存在，说明车道是切换相位关联:
    // 情况稍微复杂一些，需要创建一个临时车道关联数据，保存把当前车道方向关联当前选择的相位后，临时生成tempAssophaseList
    // 再判断tempAssophaseList中，相位id !== choosephaseid的相位数据，direction是否包含车道所选择的方向
    let checkSame = true
    if (!lastchoosephaseid) {
      for (let i = 0; i < this.associatedphaselist.length; i++) {
        let phaseid = this.associatedphaselist[i].id
        let direction = this.associatedphaselist[i].direction
        if (phaseid !== choosephaseid) {
          for (let j = 0; j < curlanedirection.length; j++) {
            if (direction.indexOf(curlanedirection[j]) !== -1) {
              checkSame = false
            }
          }
        }
      }
    } else {
      let TempAssociatedphaselist = this.createTempLanePhase(tempMotorways, editobj, choosephaseid)
      console.log('TempAssociatedphaselist', TempAssociatedphaselist)
      for (let i = 0; i < TempAssociatedphaselist.length; i++) {
        let phaseid = TempAssociatedphaselist[i].id
        let direction = TempAssociatedphaselist[i].direction
        if (phaseid !== choosephaseid) {
          for (let j = 0; j < curlanedirection.length; j++) {
            if (direction.indexOf(curlanedirection[j]) !== -1) {
              checkSame = false
            }
          }
        }
      }
    }
    return checkSame
  }
  changeItem (row, fieldarr, data) {
    for (let item of data) {
      if (item.index === row.index) {
        for (let field of fieldarr) {
          item[field] = row[field]
        }
      }
    }
  }
  ArrToMap (Arr) {
    let phaseMap = new Map()
    for (let i = 0; i < Arr.length; i++) {
      phaseMap.set(Arr[i].id, Arr[i])
    }
    return phaseMap
  }
  createTempAssophaseList (TempLaneMap) {
    let TempAssociatedphaselist = []
    let TempAssociatedphaseMap = new Map()
    TempAssociatedphaseMap = this.ArrToMap(JSON.parse(JSON.stringify(this.originphaselist)))
    for (let [key, value] of TempAssociatedphaseMap) {
      if (TempLaneMap.get(key)) {
        // 渠化车道如果关联此相位，要把渠化车道的方向覆盖初始相位的方向
        let lanevalue = TempLaneMap.get(key)
        value.direction = lanevalue.direction
      }
    }
    TempAssociatedphaselist = this.MapToArray(TempAssociatedphaseMap)
    return TempAssociatedphaselist
  }
  updateAssophaseList () {
    // 根据动态变化的渠化车道关联列表+初始上载的相位列表(包含处理后续相位的增删操作，也是变化的)，
    // 被渠化关联的相位direction被渠化组合方向替换，
    // 未被关联的相位direction还是初始相位方向
    this.associatedphaselist = []
    this.associatedphaseMap = this.ArrToMap(JSON.parse(JSON.stringify(this.originphaselist)))
    for (let [key, value] of this.associatedphaseMap) {
      if (this.lanecommonphaseMap.get(key)) {
        // 渠化车道如果关联此相位，要把渠化车道的方向覆盖初始相位的方向
        let lanevalue = this.lanecommonphaseMap.get(key)
        value.direction = lanevalue.direction
      }
    }
    console.log('associatedphaseMap', this.associatedphaseMap)
    this.associatedphaselist = this.MapToArray(this.associatedphaseMap)
    console.log('associatedphaselist', this.associatedphaselist)
    store.dispatch('SetAssociatedPhaseList', this.associatedphaselist)
  }
  MapToArray (Map) {
    let arr = []
    for (let [key, value] of Map) {
      let phaseinfo = {
        id: key,
        ...value
      }
      arr.push(phaseinfo)
    }
    return arr
  }
  increaseId () { // 实现id在之前的基础上寻找最小的
    let phaseIdList = this.originphaselist.map(ele => ele.id)
    let i = this.originphaselist.length - 1
    if (i >= 0) {
      for (let j = 1; j <= 40; j++) {
        if (!phaseIdList.includes(j)) {
          this.id = j
          return
        }
      }
    }
  }
  addOriginPhase () {
    this.increaseId()
    var phaseInitData = {
      id: this.id,
      direction: [],
      peddirection: [], // 行人方向
      mingreen: 0,
      max1: 120,
      max2: 180,
      passage: 3,
      phasewalk: 0,
      pedclear: 0,
      yellow: 3,
      redclear: 2,
      flashgreen: 0,
      redyellow: 0,
      ring: 1,
      greenpulse: 5,
      redpulse: 10,
      vehiclethresh: 30,
      pedestrianthresh: 30,
      controltype: 0, // 控制类型
      concurrent: []
    }
    this.originphaselist.push(phaseInitData)
    // 重新排序相位数组
    this.originphaselist.sort(this.compareProperty('id'))
    this.updateAssophaseList()
  }
  compareProperty (property) {
    return function (a, b) {
      var value1 = a[property]
      var value2 = b[property]
      return value1 - value2
    }
  }
  deleteOriginPhase (index) {
    this.originphaselist.splice(index, 1)
  }
  editDirPosToPhaseDireaciton (laneDirArr, lanePos) {
    // 编辑的车道转向和方位，转化成相位的direction
    let phaseDireacitonArr = laneDirArr.map(lanedir => {
      if (lanePos === 1) {
        // 东
        return lanedir
      }
      if (lanePos === 2) {
        // 西
        return 4 * 1 + lanedir
      }
      if (lanePos === 3) {
        // 南
        return 4 * 3 + lanedir
      }
      if (lanePos === 4) {
        // 北
        return 4 * 2 + lanedir
      }
    })
    return phaseDireacitonArr
  }
}
